package com.scalar.chiptrack.commons.dao;

import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DataSource;
import com.scalar.chiptrack.commons.ScreenFieldProperties;
import com.scalar.chiptrack.commons.FieldProperty;
import com.scalar.ScalarException;

import java.util.LinkedHashMap;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * User: Sujan
 * Date: Jan 20, 2009
 * Time: 3:44:04 PM
 */
public class ScreenFieldPropertiesDAO
{
     public static ScreenFieldProperties getScreenFieldProperties ( DBTransaction dbTransaction, String screenName ) throws ScalarException
     {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rset = null;
        ScreenFieldProperties props = new ScreenFieldProperties();
        try
        {
            if ( dbTransaction != null )
            {
                conn = dbTransaction.getConnection();
            }
            else
            {
                conn = DataSource.getConnection();
            }
            pstmt = conn.prepareStatement ( "SELECT [SCREEN_NAME], [FIELD_NAME], [IS_DISPLAY], [DISPLAY_FORMAT], [ORDER] FROM [SCREEN_FIELD_PROPERTIES] WHERE [SCREEN_NAME] = ?");
            pstmt.setString ( 1, screenName );

            rset = pstmt.executeQuery();
            props.setScreenName( screenName );
            LinkedHashMap map = new LinkedHashMap();
            while ( rset.next() )
            {
                FieldProperty fieldProperty = new FieldProperty();
                fieldProperty.setScreenName( rset.getString ( "SCREEN_NAME" ) );
                fieldProperty.setFieldName( rset.getString ( "FIELD_NAME" ) );
                fieldProperty.setDisplay( rset.getInt( "IS_DISPLAY") == 0 );
                fieldProperty.setDisplayFormat( rset.getString ( "DISPLAY_FORMAT" ) );
                fieldProperty.setOrder( rset.getInt ( "ORDER" ) );
                map.put ( fieldProperty.getFieldName().toUpperCase(), fieldProperty );
            }
            props.setFieldProperties( map );
        }
        catch ( Exception e )
        {
            throw new ScalarException ( "Could not load Screen Field Properties", e );
        }
        finally
        {
            if ( rset != null )
            {
                try { rset.close(); } catch ( SQLException ignore ) {}
            }
            if ( pstmt != null )
            {
                try { pstmt.close(); } catch ( SQLException ignore ) {}
            }
            if ( conn != null )
            {
                try { conn.close(); } catch ( SQLException ignore ) {}
            }
        }
        return props;
    }
}
